package com.nudge.portlet;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * This class handle the restitution of the properties defined for the portlet.
 *
 * @author Frederic Massart
 */
public class NudgePortletProperties {

    /**
     * Class logger.
     */
    private static final Logger LOG = LoggerFactory.getLogger(NudgePortletProperties.class);

    // TODO need refactore this class in order to use those properties
    private String nudgeUrlApi;
    private String applicationCode;
    private String login;
    private String password;

    /**
     * Read the settings of the monitored application from the user properties file.
     *
     * @return a map that contains all the properties
     * @throws IOException if an error occurs during the reading of the properties file.
     */
    public Map<String, Object> readPropertiesFile() throws IOException {

        // Read the nudge-portlet properties file
        Properties properties = new Properties();

        InputStream is = getClass().getResourceAsStream("/nudge-portlet.properties");
        if (is != null) {
            try {
                properties.load(is);
            } catch (IOException ioe) {
                LOG.error("Impossible to read the nudge-portlet.properties file", ioe);
                throw ioe;
            }
        } else {
            LOG.warn("The properties file is not present");
        }

        Map<String, Object> propertiesMap = new HashMap<String, Object>();

        // map the url of the nudge api
        if (StringUtils.isNotEmpty(properties.getProperty("nudge.urlApi"))) {
            propertiesMap.put("urlApi", properties.getProperty("nudge.urlApi"));
        }

        // map the applicationCode
        if (StringUtils.isNotEmpty(properties.getProperty("nudge.applicationCode"))) {
            propertiesMap.put("applicationCode", properties.getProperty("nudge.applicationCode"));
        }

        // map the login
        if (StringUtils.isNotEmpty(properties.getProperty("nudge.login"))) {
            propertiesMap.put("login", properties.getProperty("nudge.login"));
        } else {
            LOG.warn("The login is null or empty in the properties file");
            propertiesMap.put("login", "");
        }

        // map the password
        if (StringUtils.isNotEmpty(properties.getProperty("nudge.password"))) {
            propertiesMap.put("password", properties.getProperty("nudge.password"));
        } else {
            LOG.warn("The password is null or empty in the properties file");
            propertiesMap.put("password", "");
        }

        return propertiesMap;
    }
}
